//
//  CountrySelectedView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/19.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import SpriteKit
import ObjectMapper
protocol CountrySelectDelegate:class {
    func selectCountry(model:CountryModel)
}
class CountrySelectedView: UIView, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate {
    var dataSource: CountrySelectedViewController!
    weak var countrySelectDelegate:CountrySelectDelegate?
    var isUnShowCord = false
    var countryDic:NSDictionary?
    var countryArr:NSArray?
    var searchRestlt: Array = [NSDictionary]()
    var indexArr:Array<String> = []
    var isAutoPop: Bool = false
    var hiddenTableViewBool:Bool = false {
        didSet {
            self.tableView.isHidden = hiddenTableViewBool;
            self.searchCityTableView.isHidden = !hiddenTableViewBool;
        }
        
    }
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.backgroundImage = UIImage()
        searchBar.placeholder = kText("请输入关键词")
        searchBar.layer.cornerRadius = 30;
        searchBar.layer.masksToBounds = true;
        searchBar.backgroundColor = UIColor.clear
        searchBar.themeBackground = ThemeManager.ThemeColorKeys.background
        let view = searchBar.subviews.first?.subviews.last
        view?.backgroundColor = UIColor(hexStr:"#eeeeee")
        searchBar.delegate = self
        
        return searchBar
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .grouped)
        tableView.separatorStyle = .none
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.sectionIndexBackgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 0
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        return tableView
    }()
    
    lazy var searchCityTableView: UITableView = {
        let tableView = UITableView()
        tableView.isHidden = true
        tableView.separatorStyle = .none
//        tableView.sectionIndexColor = UIColor(hexStr:"#FC4880")
        tableView.sectionIndexBackgroundColor = UIColor.clear
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.tableFooterView = UIView()
        tableView.estimatedRowHeight = 0
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        return tableView
    }()
    
    init(dataSource: CountrySelectedViewController!) {
        super.init(frame: CGRect.zero)
        let path = Bundle.main.bundlePath
        let plistName:NSString = "countryData.plist"
        let finalPath:NSString = (path as NSString).appendingPathComponent(plistName as String) as NSString
//        countryArr = NSDictionary(contentsOfFile:finalPath as String)
        countryArr =  NSArray(contentsOfFile: finalPath as String)
        for dic in countryArr! {
            let letter = (dic as! NSDictionary)["countryPrefix"]
            indexArr.append(letter as! String)
        }
//        let a = ("A" as NSString).character(at: 0)
//        let z = ("Z" as NSString).character(at: 0)
//        for i in a ... z {
//            let mement = String(format: "%c", i)
//            indexArr.append(mement)
//
//        }
        self.dataSource = dataSource
        self.themeBackground = ThemeManager.ThemeColorKeys.background
        self.setUpUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
        self .addSubview(searchBar)
        searchBar.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(60)
        }
        
        self.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
        self.addSubview(searchCityTableView)
        searchCityTableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom)
            make.bottom.equalToSuperview()
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.isEqual(searchCityTableView) {
            return searchRestlt.count
        }
        let dic:NSDictionary = countryArr?.object(at: section) as! NSDictionary
        
        return (dic.object(forKey: "details") as! NSArray).count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if tableView.isEqual(searchCityTableView) {
            return 1
        }
        return (countryArr?.count)!
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if tableView.isEqual(searchCityTableView) {
            return nil
        }
        return indexArr
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView.isEqual(searchCityTableView) {
            let identifier = "searchCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? BaseTableViewCell
            if cell == nil {
                cell = BaseTableViewCell(style: .default, reuseIdentifier: identifier)
                cell?.nameLabel.snp.updateConstraints({ (make) in
                    make.left.equalToSuperview().offset(53)
                })
                cell?.backgroundColor = UIColor.clear
                cell?.contentView.addSubview((cell?.iconImage)!)
                cell?.iconImage.snp.makeConstraints({ (make) in
                    make.centerY.equalToSuperview()
                    make.left.equalToSuperview().offset(15)
                })
                cell?.contentView.addSubview((cell?.kindLabel)!)
                cell?.kindLabel.snp.makeConstraints({ (make) in
                    make.centerY.equalToSuperview()
                    make.right.equalToSuperview().offset(-16)
                })
                cell?.kindLabel.isHidden = isUnShowCord
                
            }
            cell!.textLabel!.font = UIFont.systemFont(ofSize: 14)
            let inforDic:NSDictionary = searchRestlt[indexPath.row]
            //        let dic  = array.object(at: indexPath.row) as! NSDictionary
            if AppCacheInfo.default.isEnlish {
                cell?.nameLabel.text = NSString(format: "%@", inforDic.object(forKey: "countryEnglishName") as!
                    CVarArg) as String
            }else {
                cell?.nameLabel.text = NSString(format: "%@", inforDic.object(forKey: "countryChineseName") as!
                    CVarArg) as String
            }
            cell?.iconImage.image = UIImage(named: inforDic.object(forKey: "countryFlagName") as! String)
            cell?.kindLabel.text = inforDic.object(forKey: "countryCode") as? String
            cell?.contentView.themeBackground = ThemeManager.ThemeColorKeys.background
            return cell!
            
        }
        
        let identifier = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? BaseTableViewCell
        if cell == nil {
            cell = BaseTableViewCell(style: .default, reuseIdentifier: identifier)
            cell?.nameLabel.snp.updateConstraints({ (make) in
                make.left.equalToSuperview().offset(53)
            })
            cell?.backgroundColor = UIColor.clear
            cell?.contentView.addSubview((cell?.iconImage)!)
            cell?.iconImage.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(15)
            })
            cell?.contentView.addSubview((cell?.kindLabel)!)
            cell?.kindLabel.snp.makeConstraints({ (make) in
                make.centerY.equalToSuperview()
                make.right.equalToSuperview().offset(-16)
            })
            cell?.kindLabel.isHidden = isUnShowCord
        }
        cell?.nameLabel.font = UIFont.systemFont(ofSize: 14)
        let dic:NSDictionary = countryArr?.object(at: indexPath.section) as! NSDictionary
        let inforDic:NSDictionary = (dic.object(forKey: "details") as! NSArray).object(at: indexPath.row) as! NSDictionary
//        let dic  = array.object(at: indexPath.row) as! NSDictionary
        if AppCacheInfo.default.isEnlish {
            cell?.nameLabel.text = NSString(format: "%@", inforDic.object(forKey: "countryEnglishName") as!
                CVarArg) as String
        }else {
            cell?.nameLabel.text = NSString(format: "%@", inforDic.object(forKey: "countryChineseName") as!
                CVarArg) as String
        }
        cell?.iconImage.image = UIImage(named: inforDic.object(forKey: "countryFlagName") as! String)
        cell?.kindLabel.text = inforDic.object(forKey: "countryCode") as? String
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if tableView .isEqual(searchCityTableView) {
            return 0
        }else {
            return 18
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView:UIView = UIView()
        headView.themeBackground = ThemeManager.ThemeColorKeys.background
//
        let label = BaseLabel(style: .twiceStyle)
        headView.addSubview(label)

        label.snp.makeConstraints { (make) in
            make.left.equalTo(headView).offset(15)
            make.top.bottom.right.equalTo(headView)
        }
        label.font = UIFont.systemFont(ofSize: 10)
        label.text = indexArr[section] as String
        return headView
    }
    
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        dPrint(title)
        if tableView.isEqual(searchCityTableView) {
            return NSNotFound
        }
        tableView.scrollToRow(at: IndexPath(row: 0, section: index), at: UITableViewScrollPosition.top, animated: true)
        return index
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if  tableView.isEqual(searchCityTableView) {
            let dic = searchRestlt[indexPath.row]
            let model = CountryModel(JSON: dic as! [String : Any])
            if countrySelectDelegate != nil {
                countrySelectDelegate?.selectCountry(model: model!)
            }
            self.dataSource.navigationController?.popViewController(animated: true)
            
        }else {
            let dic:NSDictionary = countryArr?.object(at: indexPath.section) as! NSDictionary
            let inforDic:NSDictionary = (dic.object(forKey: "details") as! NSArray).object(at: indexPath.row) as! NSDictionary
            
            let model = CountryModel(JSON: inforDic as! [String : Any])
            if countrySelectDelegate != nil {
                countrySelectDelegate?.selectCountry(model: model!)
//                if isAutoPop {
//                    self.dataSource.navigationController?.popViewController(animated: true)
//                }
            }
            self.dataSource.navigationController?.popViewController(animated: true)
            
        }
    }
    
    ///Mark UISearchBarDelegate
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.count != 0 {
           let queue = DispatchQueue(label: "com.roki.thread")
            queue.async {
                self.fillSearchCities(key: searchText as NSString)
                DispatchQueue.main.async {
                    self.searchCityTableView.reloadData()
                }
            }
            self.hiddenTableViewBool = true;
            return
        }
        hiddenTableViewBool = false
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.becomeFirstResponder()
        searchBar.setShowsCancelButton(true, animated: true)
        let subViews = searchBar.subviews[0].subviews
        for view in subViews {
            if view.isKind(of: UIButton.self) {
                let btn = view as! UIButton
                btn.setTitle(kText("取消"), for: UIControlState.normal)
            }
        }
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.setShowsCancelButton(false, animated: true)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        searchBar.setShowsCancelButton(false, animated: true)
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        hiddenTableViewBool = false
        searchBar.text = ""
        searchBar.setShowsCancelButton(false, animated: true)
        
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.endEditing(true)
    }
    
    
    func fillSearchCities(key:NSString) -> Void{
        searchRestlt = []
        let dataArr = indexArr as NSArray
        countryArr?.enumerateObjects { (countryDic, idex, stop) in
            let inforArr:NSArray = (countryDic as AnyObject).object(forKey: "details") as! NSArray
            
            inforArr.enumerateObjects({ (dic, index, stop) in
                let newDic = dic as! NSDictionary
                let isHaveChinese = key.isHaveChinese()
                let countryStr = newDic.object(forKey: "countryChineseName") as! String
                let enStr = newDic.object(forKey: "countryEnglishName") as! String
                
                if enStr.lowercased().contains(key.lowercased) {
                    searchRestlt.append(newDic)
                    return
                }
                
                if isHaveChinese {
                    if (countryStr as NSString).contains(key as String) {
                        searchRestlt.append(newDic)
                    }
                    return
                }
                
                let firstCharactor = self.firstCharactor(aString: countryStr )
                let pinyin = self.chineseCharactor(aString: countryStr ).replacingOccurrences(of: " ", with: "").uppercased()
                if firstCharactor.contains(key.uppercased) || pinyin.contains(key.uppercased) {
                    searchRestlt.append(newDic)
                }
            })
        }
            
    }
        
    func firstCharactor(aString:String) -> String {
        let str = NSMutableString(string: aString) as CFMutableString
        CFStringTransform(str, nil, kCFStringTransformMandarinLatin, false)
        CFStringTransform(str, nil, kCFStringTransformStripDiacritics, false)
        let pinYin = (str as String) .capitalized
        return pinYin
    }
    
    func chineseCharactor(aString:String) -> String {
        let pinYin = self.firstCharactor(aString: aString)
        let arr = pinYin.components(separatedBy: " ")
        var firstCharactors = ""
        for itme in arr.enumerated() {
          firstCharactors = firstCharactors +  itme.element.suffix(1)
        }
        return firstCharactors
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
